<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="nn"  placeholder="设备名称" style="width: 200px;" class="filter-item" />
      <el-input  placeholder="设备类型" style="width: 200px;" class="filter-item" />
      <el-select v-model="simp" placeholder="重要等级" clearable style="width: 150px" class="filter-item">
        <el-option v-for="item in ImpOpt" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAdd">
        添加一种设备
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handlePi">
        批量添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleDownload">
        下载批量添加模板
      </el-button>
    </div>


    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="设备名称" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name}}</span>
        </template>
      </el-table-column>


      <el-table-column label="设备图片" min-width="150px" align="center">
        <template slot-scope="{row}">
          <img :src="row.img" width="100" height="100">
        </template>
      </el-table-column>

      <el-table-column label="设备类型" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type}}</span>
        </template>
      </el-table-column>

      <el-table-column label="重要等级" width="150px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.imp | impFilter">
            {{ row.imp }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="设备总数" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.num}}</span>
        </template>
      </el-table-column>

      <el-table-column label="在库数目" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.in}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑信息
          </el-button>
          <el-button size="mini" type="success" @click="handleAddInstance(row)">
            增加设备实例
          </el-button>
          <el-button  size="mini" @click="seeList(row)">
            查看设备
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除设备
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="tot" :page.sync="page" :limit.sync="limit" @pagination="getList" />


    <el-dialog :title="dialogStatus==='create'?'添加一种设备':'修改设备信息'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">

        <el-form-item label="设备名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item label="设备类别" prop="type">
          <el-input v-model="temp.type" />
        </el-form-item>

        <el-form-item label="重要等级" prop="imp">
          <el-select v-model="temp.imp" class="filter-item" placeholder="选择设备重要等级">
            <el-option v-for="item in ImpOpt" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备图片" prop="img">
          <el-upload
            class="avatar-uploader"
            action="no-acction"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="temp.img!=''" :src="temp.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>




      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>

    </el-dialog>

    <el-dialog title="批量添加设备" :visible.sync="dialogPI">

      <el-upload
        class="upload-demo"
        action="/dev-api/device/ps"
        :limit="1"
        :before-remove="bfPI">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx文件，且不超过500kb</div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPI = false">
          取消
        </el-button>
        <el-button type="primary" @click="PICreate">
          确认
        </el-button>
      </div>

    </el-dialog>


    <el-dialog title="添加设备实例" :visible.sync="dialogInstance">
      <el-form ref="inf" :rules="infrules" :model="inftemp" label-position="left" label-width="130px" style="width: 400px; margin-left:50px;">


        <el-form-item label="设备RFID" prop="rfid">
          <el-input v-model="inftemp.rfid" />
        </el-form-item>

        <el-form-item label="设备所在仓库" prop="base" >
          <el-input v-model="inftemp.base" />
        </el-form-item>


      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogInstance = false">
          取消
        </el-button>
        <el-button type="primary" @click="createInstance">
          确认
        </el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {fetchList,createDevice,updateDevice,deleteDevice,addInstance} from "@/api/device";
import Pagination from '@/components/Pagination'
export default {
  components:{
    Pagination
  },
  filters: {
    impFilter(status) {
      const impMap = {
        一般: 'success',
        重要: 'danger'
      }
      return impMap[status]
    },
  },
  methods:{
    onlYiMp(){
      let nd=[]
      for(let i in this.list){
        let t=this.list[i]
        if(t.imp===this.simp)
          nd.push(t)
      }
      this.list=nd
    },
    bfPI(){
      return false
    },
    PICreate(){
      this.$message({
        type: 'success',
        message: '添加成功!'
      });
      this.dialogPI=false
      this.loadList()
    },
    handlePi(){
      this.dialogPI=true
    },
    handleDelete(row){
      this.$confirm('此操作将删除设备及其实例, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice({
          id:row.id
        }).then(()=>{
          this.loadList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
      });
    },
    handleUpdate(row){
      this.temp.id=row.id
      this.temp.name=row.name
      this.temp.img=row.img
      this.temp.type=row.type
      this.temp.imp=row.imp
      this.dialogStatus="update"
      this.dialogFormVisible=true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSearch(){
      fetchList().then((res)=>{
        this.list=res.data
        if(this.simp!=="")
          this.onlYiMp()
        if(this.nn!=="")
          this.onLyNN()
      })

    },
    onLyNN(){
      let nd=[]
      for(let i in this.list){
        let t=this.list[i]
        if(t.name===this.nn)
          nd.push(t)
      }
      this.list=nd
    },
    handleAvatarSuccess(){

    },
    handleAddInstance(row){
      this.inftemp={
        rfid:"",
        base:""
      }
      this.inftemp.id=row.id
      this.dialogInstance=true
      this.$nextTick(() => {
        this.$refs['inf'].clearValidate()
      })
    },
    beforeAvatarUpload(file){
      const fd = new FileReader();
      fd.readAsDataURL(file)
      fd.onload=()=>{
        this.temp.img=fd.result
      }
      return false
    },
    createData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createDevice(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.loadList()
            this.$notify({
              title: 'Success',
              message: '创建设备成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    createInstance(){
      this.$refs['inf'].validate((valid) => {
        if (valid) {
          addInstance(this.inftemp).then((res) => {
            this.dialogInstance = false
            this.loadList()
            this.$notify({
              title: 'Success',
              message: '创建设备实例成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    seeList(row){
      this.$router.push({path:"/device/list",query:{id:row.id}})
    },
    updateData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateDevice(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.loadList()
            this.$notify({
              title: 'Success',
              message: '更新信息成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    resetTemp(){
      this.temp={
        id:0,
        name:"",
        type:"",
        imp:"",
        img:""
      }
    },
    handleAdd(){
      this.resetTemp()
      this.dialogStatus="create"
      this.dialogFormVisible=true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    loadList(){
      fetchList().then((res)=>{
        this.list=res.data
      })
    },
    getList(){

    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['设备名称', '设备类型', "重要等级", '设备RFID', '设备所在仓库']
        excel.export_json_to_excel({
          header: tHeader,
          data:[],
          filename: "设备批量添加模板",
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
  },
  data(){
    return{
      nn:"",
      downloadLoading:false,
      simp:"",
      total:5,
      page:1,
      limit:5,
      inftemp:{
        id:0,
        rfid:"",
        base:""
      },
      dialogInstance:false,
      dialogStatus:"create",
      ImpOpt:[
        "",
        "一般",
        "重要",
        "非常重要",
      ],
      infrules:{
        rfid: [{ required: true, message: '设备RFID不能为空', trigger: 'change' }],
        base: [{ required: true, message: '设备所在仓库不能为空', trigger: 'change' }],
      },
      rules: {
        type: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        name: [{ required: true, message: '设备名不能为空', trigger: 'change' }],
        imp: [{  required: true, message: '重要等级不能为空', trigger: 'change' }],
      },

      dialogFormVisible:false,
      temp:{
        name:"",
        type:"",
        imp:"",
        img:"",
      },
      list:[],
      dialogPI:false
    }
  },
  computed:{
    tot(){
      return this.list.length
    }
  },
  mounted() {
    this.loadList()
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
